// pages/user/user.js
import { Order } from './notPay-model.js'
const app = getApp()
const order = new Order()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        wxUid: '',
        storeNo: '',
        employeNo:'',
        leftBar: '22',
        nowId: 1,
        orderList: [],
        hasMore: false,
        page: 1,
        noneData: false,
        threeOrderCount: null,
        allowClick: true,
        soldoutList: null,
        loadDone: false
        
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.showLoading({
            title: '加载中',
        })
        this.setData({
            storeNo: wx.getStorageSync('storeNo'),
            wxUid: wx.getStorageSync('wxUid'),
        })
        this.commonRequest('W', '', '')
    },
    //   公共的请求
    commonRequest(orderStatus, logisticStatus, pulldown) {
        let { page, storeNo, orderList, wxUid } = this.data
        let timer = null
        let params = {
            "data": {
                wxUid,
                "orderStatus": orderStatus,
                "page": '' + page
            }
        }
        this.commonGetOrderCount()
        order.getOrder(params, res => {
            if (res.status) {
                wx.hideLoading()
                wx.stopPullDownRefresh()
                console.log(res)
                // clearInterval(timer)
                    
                res.data.forEach(val => {
                    val.update_time = order.formate(val.update_time)
                    let nowPrice
                    if (val.couponAmount) {
                        nowPrice = ((Number(val.price) + Number(val.postage)) * 10 - (Number(val.couponAmount)) * 10) / 10
                    } else {
                        nowPrice = Number(val.price) + Number(val.postage)
                    }
                    val.price = nowPrice
                })
                console.log(res.data)
                if (res.total > orderList.length && pulldown !== 'pulldown') {

                    orderList = [...orderList, ...res.data]
                    // console.log('orderList', orderList)

                    this.setData({
                        orderList,
                        hasMore: true,
                        loadDone: true
                    })
                } else if (pulldown == 'pulldown') {
                    orderList = res.data
                    // console.log('orderList-pull', orderList)
                    this.setData({
                        orderList,
                        hasMore: true,
                        loadDone: true
                    })
                } else {
                    this.setData({
                        hasMore: false,
                        loadDone: true
                    })
                }
                if (res.total == orderList.length) {
                    this.setData({
                        hasMore: false,
                        loadDone: true
                    })
                }
                if (res.total == 0) {
                    this.setData({
                        noneData: true,
                        hasMore: false,
                        loadDone: true
                    })
                }
                clearInterval(timer)
                this.countDown()                
                timer = setInterval(()=>{
                    this.countDown()
                },1000)
            } else {
                wx.hideLoading()
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
                wx.stopPullDownRefresh()
            }
        })
    },
    // 定时器
    countDown(){
        let { orderList } = this.data
        orderList.forEach((val) => {
            val.expire = order.countdown(val.expire_time)
        })
        this.setData({
            orderList
        })
    },
    //   跳转详情
    jumpDetail(e) {
        let { storeNo } = this.data;
        let id = order.getDataSet(e, "id");
        wx.navigateTo({
            url: '/pages/orderDetail/orderDetail?orderId=' + id + '&storeNo=' + storeNo,
        })
    },
    jumpGoods(e){
        let { storeNo } = this.data;
        let id = order.getDataSet(e, "id");
        wx.navigateTo({
            url: '/pages/product/product?id=' + id + '&storeNo=' + storeNo,
        })
    },
    // 取消订单
    cancelOrder(e){
        var id = e.currentTarget.dataset.id
        let that = this
        wx.showModal({
            title: '提示',
            content: '确认取消该订单吗？',
            success: function (res) {
                if (res.confirm) {
                    console.log('用户点击确定')
                    let params = {
                        "data": {
                            "orderId": "" + id
                        }
                    }
                    wx.showLoading({
                        title: '加载中',
                    })
                    order.cancelOrder(params, res => {
                        if (res.status) {
                            wx.hideLoading()
                            wx.showToast({
                                title: '取消成功',
                                icon: 'success',
                                duration: 2000,
                                success() {
                                    setTimeout(() => {
                                        that.onPullDownRefresh()
                                    }, 1500)
                                }
                            })
                        }
                    })

                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    //   删除订单
    deleteOrder(e) {
        var id = e.currentTarget.dataset.id
        let that = this
        wx.showModal({
            title: '提示',
            content: '确认删除该订单吗？',
            success: function (res) {
                if (res.confirm) {
                    console.log('用户点击确定')
                    let params = {
                        "data": {
                            "orderId": "" + id
                        }
                    }
                    wx.showLoading({
                        title: '加载中',
                    })
                    order.deleteOrder(params, res => {
                        if (res.status) {
                            wx.hideLoading()
                            wx.showToast({
                                title: '删除成功',
                                icon: 'success',
                                duration: 2000,
                                success() {
                                    setTimeout(() => {
                                        that.onPullDownRefresh()
                                    }, 1500)
                                }
                            })
                        }
                    })

                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    trace(e) {
        var id = e.currentTarget.dataset.id
        var addressId = e.currentTarget.dataset.address
        wx.navigateTo({
            url: '/pages/orderTrace/orderTrace?addressId=' + addressId + '&orderId=' + id
        })
    },
    //立即支付
    pay(e) {
        let that = this
        var dataset = e.currentTarget.dataset
        var id = dataset.id
        var addressId = dataset.address
        let { orderList, allowClick} = this.data
        console.log(id, addressId)
        let wxuid = wx.getStorageSync('wxUid');
        // app.aldstat.sendEvent('立即支付', this.data.employeNo);
        
        this.setData({
            allowClick: false
        })
        wx.showLoading({
            title: '加载中',
        })
        //   查询订单地址是否有效
        order.getUserAddressById({
            "data": {
                id: '' + addressId
            }
        }, res => {
            if (res.status) {
                if (!allowClick) { console.log('多点拦截'); return }
                //   如果地址关联了并且状态不是删除的状态就可以发起支付
                if (addressId && res.data.status != 1) {
                    let getAddress = res.data
                    let params = {
                        data: {
                            "wxuid": wxuid,
                            "orderId": id,
                            "contacts": getAddress.contacts,
                            "mobilePhone": getAddress.mobilePhone,
                            "detailedAddress": getAddress.detailedAddress,
                            "tradeType": "JSAPI"

                        }
                    }
                    console.log(params)

                    order.wxPay(params, res => {
                        wx.hideLoading()
                        if (res.status) {
                            let data = res.data
                            console.log('res', res, res.data, 'prepay_id=' + data.miniPaySign, data.stockList)
                            if (data.result_code == "SUCCESS" && data.return_code == "SUCCESS") {

                                console.log('success')
                                wx.requestPayment({
                                    'timeStamp': '' + data.miniTimeStamp,
                                    'nonceStr': '' + data.miniNonceStr,
                                    'package': 'prepay_id=' + data.prepay_id,
                                    'signType': 'MD5',
                                    'paySign': '' + data.miniPaySign,
                                    'success': function (result) {
                                        console.log('pay', result)
                                        order.reduceGoodsStock({
                                            "data": {
                                                orderId: id,
                                                formId: e.detail.formId
                                            }
                                        }, reduce => {
                                            that.onLoad()
                                        })
                                        app.aldstat.sendEvent('付款', data.employeNo);
                                    },
                                    'fail': function (result) {
                                        that.setData({
                                            allowClick: true
                                        })
                                    }
                                })
                            } else if (data.stockList && data.stockList.length > 0) {
                                console.log(data.stockList)
                                this.setData({
                                    soldoutList: data.stockList,
                                    allowClick: true
                                })
                            }
                        } else {
                            wx.showToast({
                                title: '服务器错误',
                                icon: 'none'
                            })                            
                            this.setData({
                                allowClick: true
                            })
                        }
                    })
                } else {
                    let { storeNo } = this.data;
                    wx.hideLoading()
                    console.log('无地址关联')
                    wx.navigateTo({
                        url: '/pages/orderDetail/orderDetail?orderId=' + id + '&storeNo=' + storeNo,
                    })
                    this.setData({
                        allowClick: true
                    })
                }

            } else {
                wx.hideLoading()
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
            }
        })
    },
    soldoutBack() {
        this.setData({
            soldoutList: null,
            allowClick: true

        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var { page, hasMore, loadDone } = this.data;
        /**
         * 此处加上数据大小的判断
         */
        if (loadDone){
            wx.pageScrollTo({
                scrollTop: 0,
                duration: 0
            })
            this.setData({
                page: 1,
                allowClick: true
            })
            this.commonRequest('W', '', 'pulldown')        
        }
    },
    showAddAddress() {
        this.setData({
            dialogShow: true
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.setData({
            page: 1,
        })
        this.commonRequest('W', '', 'pulldown')
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        var { page, hasMore, nowId } = this.data;
        console.log('bottom', nowId)
        /**
         * 此处加上数据大小的判断
         */
        nowId = +nowId
        if (hasMore) {
            this.setData({
                page: page + 1
            })
            this.commonRequest('W', '', '')            
        }
    },

    commonGetOrderCount() {
        let parmas = {
            "data": {
                wxUid: this.data.wxUid
            }
        }
        order.getOrderCount(parmas, res => {
            if (res.status) {
                this.setData({
                    threeOrderCount: res.data
                })

            } else {
                wx.hideLoading()
                wx.showToast({
                    title: '服务器错误',
                    icon: 'none'
                })
                wx.stopPullDownRefresh()
            }
        })
    },
   
})